package com.unkow.first.telegram.util;


import lombok.extern.slf4j.Slf4j;
import org.cloud.utils.EnvUtil;
import org.cloud.utils.SpringContextUtil;
import org.springframework.context.annotation.Lazy;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChat;
import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChatMember;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage.SendMessageBuilder;
import org.telegram.telegrambots.meta.api.objects.Chat;
import org.telegram.telegrambots.meta.api.objects.chatmember.ChatMember;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

/**
 * telegram 消息发送工具类，用通用的内置消息机器人发送
 */
@Slf4j
public final class TelMsgSendUtil {

    private final TelegramLongPollingBot defaultTelBot;
    private final String validateChatId;

    @Lazy
    private TelMsgSendUtil() {
        defaultTelBot = SpringContextUtil.getBean("telegramLongPollingBot", TelegramLongPollingBot.class);
        validateChatId = EnvUtil.single().getEnv("system.telegram.bot.config.VALIDATE_CHAT_ID");
    }

    private final static TelMsgSendUtil handler = new TelMsgSendUtil();


    public static TelMsgSendUtil single() {
        return handler;
    }

    public int sendMessage(final String message) {
        return sendMessage(validateChatId, message);
    }

    public int sendMessage(final String chatId, final String message) {
        return sendMessage(chatId, message, null);
    }

    /**
     * @param chatId    聊天群ID
     * @param message   消息内容
     * @param parseMode 解析方式，Markdown、MarkdownV2、html
     * @return
     */
    public int sendMessage(final String chatId, final String message, String parseMode) {
        return sendMessage(null, chatId, message, parseMode, null);
    }

    public int sendMessage(final String chatId, final String message, String parseMode, ReplyKeyboard replyMarkup) {
        return sendMessage(null, chatId, message, parseMode, replyMarkup);
    }

    public int sendMessageMarkdown(final String message) {
        return sendMessageMarkdown(validateChatId, message);
    }

    public int sendMessageMarkdown(final String chatId, final String message) {
        return sendMessage(chatId, message, "MarkdownV2");
    }

    public int sendMessageMarkdown(final String chatId, final String message, ReplyKeyboard replyMarkup) {
        return sendMessage(null, chatId, message, "MarkdownV2", replyMarkup);
    }


    /**
     * @param chatId    聊天群ID
     * @param message   消息内容
     * @param parseMode 解析方式，Markdown、MarkdownV2、html
     * @return
     */
    public int sendMessage(String baseURL, final String chatId, String message, String parseMode, ReplyKeyboard replyMarkup) {
        try {
            if("MarkdownV2".equalsIgnoreCase(parseMode)){
                message = TelMsgSendUtil.escapeMarkdownV2(message);
            }
            SendMessageBuilder messageBuilder = SendMessage.builder().chatId(chatId).text(message);
            if (replyMarkup != null) {
                messageBuilder.replyMarkup(replyMarkup);
            }
            if (StringUtils.hasLength(parseMode)) {
                messageBuilder.parseMode(parseMode);
            }

            DefaultBotOptions defaultBotOptions = new DefaultBotOptions();
            if (!ObjectUtils.isEmpty(baseURL)) {
                defaultBotOptions.setBaseUrl(baseURL);
            }
            defaultTelBot.execute(messageBuilder.build());
        } catch (Exception e) {
            log.error("Tg消息发送失败,错误信息：{},消息内容:{}", e.getMessage(), message, e);
            return 500;
        }
        return 200;
    }

    public boolean isUserInChannel(String channelId, String userId) {
        ChatMember chatMember = getChatMember(channelId, userId);
        if (chatMember == null) {
            return false;
        }
        String status = chatMember.getStatus();
        return "member".equals(status) || "administrator".equals(status) || "creator".equals(status);
    }

    public ChatMember getChatMember(String channelId, Long userId) {
        try {
            GetChatMember getChatMember = new GetChatMember();
            getChatMember.setChatId(channelId);
            getChatMember.setUserId(userId);
            return defaultTelBot.execute(getChatMember);
        } catch (TelegramApiException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 机器人只能获取到通过名称只能获取到自己的info信息
     *
     * @param channelId
     * @param username
     * @return
     */
    public ChatMember getChatMember(String channelId, String username) {
        try {
            Chat chat = getUserIdByUsername(username);
            if (chat == null) {
                return null;
            }
            GetChatMember getChatMember = new GetChatMember();
            getChatMember.setChatId(channelId);
            getChatMember.setUserId(chat.getId());
            return defaultTelBot.execute(getChatMember);
        } catch (TelegramApiException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    public Chat getUserIdByUsername(String username) {
        try {
            GetChat getChat = new GetChat();
            getChat.setChatId(username);
            return defaultTelBot.execute(getChat);
        } catch (TelegramApiException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    // In all other places characters '_', '*', '[', ']', '(', ')', '~', '', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!' must be escaped with the preceding character '\'.
    public static String escapeMarkdownV2(String input) {
        if (input == null) {
            return null;
        }
        // 需要转义的特殊字符
        char[] specialChars = {'_', '(', ')', '#', '+', '-', '=', '{', '}', '.'};
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < input.length(); i++) {
            char currentChar = input.charAt(i);

            // 检查当前字符是否需要转义
            boolean needsEscape = false;
            for (char specialChar : specialChars) {
                if (currentChar == specialChar) {
                    needsEscape = true;
                    break;
                }
            }
            if (needsEscape) {
                result.append('\\');
            }
            result.append(currentChar);
        }

        return result.toString();
    }
}


